# -*- coding: utf-8 -*-
__author__ = 'BuddyHolly'

import os
from PIL import Image, ImageDraw, ImageFont


# =========================================================
# *** 传统水印生成及添加 ***
#
# img_path_name：原图路径
# text：水印文字
#
# 变换后的图像存在img_path_name处（更新img且后缀变为png），无返回值
# =========================================================

def com_wm(img_path_name, text):
    image = Image.open(img_path_name)
    font = ImageFont.truetype(os.path.join(os.getcwd(), r'app\static\fonts', 'NotoSansCJK-Black.ttc'), 36)
    # 添加背景
    new_img = Image.new('RGBA', (image.size[0] * 3, image.size[1] * 3), (0, 0, 0, 0))
    new_img.paste(image, image.size)

    # 添加水印
    font_len = len(text)
    rgba_image = new_img.convert('RGBA')
    text_overlay = Image.new('RGBA', rgba_image.size, (255, 255, 255, 0))
    image_draw = ImageDraw.Draw(text_overlay)

    for i in range(0, rgba_image.size[0], font_len * 40 + 100):
        for j in range(0, rgba_image.size[1], 200):
            image_draw.text((i, j), text, font=font, fill=(0, 0, 0, 50))
    text_overlay = text_overlay.rotate(-45)
    image_with_text = Image.alpha_composite(rgba_image, text_overlay)

    # 裁切图片
    image_with_text = image_with_text.crop((image.size[0], image.size[1], image.size[0] * 2, image.size[1] * 2))

    # 删除img原图
    os.remove(img_path_name)

    # 保存添加过水印的图
    save_path_name = img_path_name[:-4] + '.png'

    image_with_text.save(save_path_name)
